<?php
/**
 * Created by PhpStorm.
 * User: huanghao
 * Date: 2019/10/10
 * Time: 10:48 PM
 */

namespace app\index\controller;


use GuzzleHttp\Client;
use think\Db;
use think\Response;

class Article extends Base
{
    /**
     *  列表
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $page = \request()->post("page") ?? 1;
        $pageSize = ($page - 1) * 15;
        $list = Db::table('article')
            ->order([
                'sort' => 'asc',
                'publish_time' => 'desc'
            ])
            ->limit($pageSize,15)
            ->field('url', true)
            ->select();
        $data['data'] = $list;
        $data['msg'] = '获取成功~';
        return $this->_toSuccess($data);
    }

    /**
     *  详情
     *
     * @throws \Exception
     * @return null|string|string[]
     */
    public function detail()
    {
        $id = request()->get('id');
        $article = Db::table('article')
            ->where('id', $id)
            ->field('url, mp_name')
            ->find();
        $http = new Client();
        $response = $http->get($article['url']);
        $contents = $response->getBody()->getContents();

        $contents = preg_replace(
            '/data-src="https:\/\/mmbiz..*?.cn(\/mmbiz_.*?\/.*?\/640\?wx_fmt=.*?)"/',
            'data-src="https://'.$_SERVER['HTTP_HOST'].'/index/article/image/?path=${1}"',
            $contents
        );

        $contents = preg_replace('/<p style="white-space: normal;text-align: center;">.*?<\/p>/', '', $contents, 1);
        $contents = preg_replace('/<p style="white-space: normal;max-width: 100%;min-height: 1em;.*?<\/p>/', '', $contents);
        $contents = preg_replace('/'.$article['mp_name'].'/', '暮乐朝欢', $contents);

        return $contents;
    }

    public function image()
    {
        $path = request()->get('path');
        $http = new Client([
            'headers' => [
                'host' => 'mmbiz.qpic.cn'
            ]
        ]);
        $url = 'https://mmbiz.qpic.cn'.$path.'';
        $response = $http->get($url, []);

        return Response::create($response->getBody()->getContents(), '', 200, [
            'Content-type', 'image/webp'
        ]);

    }


}